<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerModal"
    :minHeight="100"
    :title="getTitle"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, ref, computed, unref } from 'vue';
  // import { useMessage } from '/@/hooks/web/useMessage';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { accountFormSchema } from './account.data';
  // import { postUsers, putUsers } from '/@/api/sys/user';
  // const { createMessage } = useMessage();
  import { useI18n } from '/@/hooks/web/useI18n';
  import { addUser, editUser } from '/@/api/sys/user';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useUserStoreWithOut } from '/@/store/modules/user';
  import { MD5 } from 'crypto-js';

  const { t } = useI18n();
  let validatePass2 = ({ values }) => {
    return [
      {
        required: true,
        validator: (_, value) => {
          if (!value) {
            return Promise.reject(t('请确认密码'));
          }
          if (value !== values.password) {
            return Promise.reject('两次输入的密码不一致');
          }
          return Promise.resolve();
        },
      },
    ];
  };

  export default defineComponent({
    name: 'AccountModal',
    components: { BasicModal, BasicForm },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const isUpdate = ref(true);
      const [
        registerForm,
        {
          setFieldsValue,
          appendSchemaByField,
          removeSchemaByFiled,
          updateSchema,
          resetFields,
          validate,
        },
      ] = useForm({
        labelWidth: 100,
        schemas: accountFormSchema,
        showActionButtonGroup: false,
        actionColOptions: {
          span: 23,
        },
      });
      // let oldUserName: string;
      const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
        resetFields();
        console.log(data);
        setModalProps({ confirmLoading: false });
        isUpdate.value = !!data?.isUpdate;

        if (unref(isUpdate)) {
          // oldUserName = data.record.username;
          setFieldsValue({
            ...data.record,
          });
        }

        if (!unref(isUpdate)) {
          appendSchemaByField(
            {
              field: 'enterpwd',
              label: '确认密码',
              component: 'InputPassword',
              dynamicRules: validatePass2,
            },
            'password',
          );
        } else {
          removeSchemaByFiled('enterpwd');
        }
        updateSchema([
          {
            field: 'password',
            required: !unref(isUpdate),
            show: !unref(isUpdate),
          },
        ]);

        // const treeData = await getDeptList();
        // updateSchema([
        //   {
        //     field: 'pwd',
        //     show: !unref(isUpdate),
        //   },
        //   {
        //     field: 'dept',
        //     componentProps: { treeData },
        //   },
        // ]);
      });

      const userStore = useUserStoreWithOut();

      const getTitle = computed(() => (!unref(isUpdate) ? '添加用户' : '编辑用户'));
      const { createMessage } = useMessage();
      async function handleSubmit() {
        try {
          const values = await validate();
          setModalProps({ confirmLoading: true });
          // TODO custom api
          console.log(values);
          if (unref(isUpdate)) {
            const nId = values.id;
            delete values.id;
            editUser(nId, values).then(
              () => {
                closeModal();
                createMessage.success('编辑用户成功');
                emit('success');
              },
              () => {
                // 业务层不提示了
                // createMessage.error('添加用户失败');
              },
            );
          } else {
            addUser({
              ...values,
              pid: userStore.getUserInfo.id,
              password: MD5(values.password).toString(),
            }).then(
              () => {
                closeModal();
                createMessage.success('添加用户成功');
                emit('success');
              },
              () => {
                // 业务层不提示了
                // createMessage.error('添加用户失败');
              },
            );
          }
        } catch (e) {
          console.log(e);
        } finally {
          setModalProps({ confirmLoading: false });
        }
      }

      return { registerModal, registerForm, getTitle, handleSubmit, t };
    },
  });
</script>
